package com.taokatao.cardmee.business.carddetail;

import android.Manifest;
import android.app.Dialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.net.Uri;
import android.os.Bundle;
import android.support.v4.app.ActivityCompat;
import android.text.SpannableString;
import android.text.Spanned;
import android.text.TextUtils;
import android.text.style.BackgroundColorSpan;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.amap.api.location.AMapLocation;
import com.amap.api.location.AMapLocationClient;
import com.amap.api.location.AMapLocationListener;
import com.amap.api.maps2d.AMapUtils;
import com.amap.api.maps2d.model.LatLng;
import com.bumptech.glide.Glide;
import com.makeramen.roundedimageview.RoundedImageView;
import com.taokatao.cardmee.ActivityCollector;
import com.taokatao.cardmee.App;
import com.taokatao.cardmee.BaseActivity;
import com.taokatao.cardmee.BusEvent;
import com.taokatao.cardmee.C;
import com.taokatao.cardmee.R;
import com.taokatao.cardmee.Utils;
import com.taokatao.cardmee.WebActivity;
import com.taokatao.cardmee.api.AMapWebApiManager;
import com.taokatao.cardmee.api.ApiManager;
import com.taokatao.cardmee.api.RespInfo;
import com.taokatao.cardmee.api.RespWrapper;
import com.taokatao.cardmee.api.SubscriberAdapter;
import com.taokatao.cardmee.api.model.CardDetailInfo;
import com.taokatao.cardmee.api.model.CardShareInfo;
import com.taokatao.cardmee.api.model.MapPOI;
import com.taokatao.cardmee.api.security.ServiceUrlProvider;
import com.taokatao.cardmee.business.MainActivity;
import com.taokatao.cardmee.business.cardcode.CardCodeActivity;
import com.taokatao.cardmee.business.cardcrud.CardInfoEditActivity;
import com.taokatao.cardmee.business.map.AMapActivity;
import com.taokatao.cardmee.common.widget.AlertDialog;
import com.taokatao.cardmee.common.widget.ShareDialog;
import com.taokatao.cardmee.common.widget.SheetDialog;
import com.taokatao.cardmee.common.widget.TitleLayout;
import com.taokatao.cardmee.db.model.Card;
import com.umeng.socialize.ShareAction;
import com.umeng.socialize.UMShareListener;
import com.umeng.socialize.bean.SHARE_MEDIA;
import com.umeng.socialize.media.UMImage;
import com.yanzhenjie.permission.AndPermission;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

public class CardDetailActivity extends BaseActivity implements View.OnClickListener, AMapLocationListener,
        ActivityCompat.OnRequestPermissionsResultCallback, TitleLayout.Callback {

    @BindView(R.id.l_title) TitleLayout lTitle;
    @BindView(R.id.i_background) RoundedImageView iBackground;
    @BindView(R.id.t_grade) TextView tGrade;
    @BindView(R.id.i_logo) ImageView iLogo;
    @BindView(R.id.t_card_name) TextView tCardName;
    @BindView(R.id.t_number) TextView tNumber;
    @BindView(R.id.i_code) ImageView iCode;
    @BindView(R.id.l_rights) View lRights;
    @BindView(R.id.t_rights_title) TextView tRightsTitle;
    @BindView(R.id.t_rights_desc) TextView tRightsDesc;
    @BindView(R.id.t_rights_tags) TextView tRightsTags;
    @BindView(R.id.i_rights_url) ImageView iRightUrl;
    @BindView(R.id.l_coupon) View lCoupon;
    @BindView(R.id.t_coupon_title) TextView tCouponTitle;
    @BindView(R.id.t_coupon_desc) TextView tCouponDesc;
    @BindView(R.id.i_coupon_url) ImageView iCouponUrl;
    @BindView(R.id.l_promotion) View lPromotion;
    @BindView(R.id.l_primary_promotion) View lPrimaryPromotion;
    @BindView(R.id.t_promotion_title) TextView tPromotionTitle;
    @BindView(R.id.t_promotion_desc) TextView tPromotionDesc;
    @BindView(R.id.i_promotion_url) ImageView iPromotionUrl;
    @BindView(R.id.l_sub_promotions) LinearLayout lSubPromotions;
    @BindView(R.id.l_official_website) View lOfficialWebSite;
    @BindView(R.id.l_line_location) View lLineLocation;
    @BindView(R.id.l_spacing_location) View lSpacingLocation;
    @BindView(R.id.l_location) View lLocation;
    @BindView(R.id.t_address) TextView tAddress;
    @BindView(R.id.t_distance) TextView tDistance;
    @BindView(R.id.l_line_address_tel) View lLineAddressTel;
    @BindView(R.id.l_address) View lAddress;
    @BindView(R.id.l_address_tel) View lAddressTel;
    @BindView(R.id.t_address_tel) TextView tAddressTel;
    @BindView(R.id.l_card_detail_item) View lCardDetailItem;

    // 分店预约功能展示区域
    @BindView(R.id.l_book) View lBook;
    @BindView(R.id.l_sub_courses) LinearLayout lSubCourses;

    // 分店内容展示区域(余额;积分;套餐数)
    @BindView(R.id.l_s) View lS;
    @BindView(R.id.t_balance) TextView tBalance;
    @BindView(R.id.t_integral) TextView tIntegral;
    @BindView(R.id.t_product_count) TextView tProductCount;

    @BindView(R.id.l_score) View lScore;

    @BindView(R.id.l_ads) LinearLayout lAds;
    @BindView(R.id.l_banner) LinearLayout lBanner;

    private SheetDialog dlgSheet;

    private int styleColor;
    private boolean isCustomMode;
    private boolean hasStartLocation;
    private boolean hasCurrLatlng;
    private Card c;
    private CardDetailInfo info;

    private AMapLocationClient locationClient;
    private double myLat, myLng, targetLat, targetLng;
    private String targetCardName, targetAddress;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_card_detail);
        ButterKnife.bind(this);

        c = (Card) getIntent().getSerializableExtra("extra_card");
        isCustomMode = C.settings.BUSINESS_OTHER_ID == c.getBusinessId().longValue();

        locationClient = App.i().getAMapLocationClient();
        locationClient.setLocationListener(this);

        lTitle.setCallback(this);

        resetBasicInfo();

        if (!isCustomMode) {
            requestObtainCardDetail();
        }
        requestUpdateCardUseCount();
    }

    @Override
    public void onMenuClick(TitleLayout lTitle, String flag) {
        Utils.onMobEvent(this, "clickEditButtonOfCardDetails");
        showSheetDialog();
    }

    private void requestUpdateCardUseCount() {
        ApiManager.i().updateCardUseCount(this, c.getMCardId(), 1, new SubscriberAdapter<RespWrapper<RespInfo>>() {
        }.errorToast(false));
    }

    @Override
    public void onLocationChanged(AMapLocation loc) {
        locationClient.stopLocation();
        if (hasCurrLatlng) return;

        String locationResult;
        if (loc != null) {
            if (loc.getErrorCode() == 0) {
                myLat = loc.getLatitude();
                myLng = loc.getLongitude();
                hasCurrLatlng = true;
                locationResult = loc.getAddress() + "[lat:" + myLat + "#lng:" + myLng + "]";

                String searchContent = c.getBusinessName();
                if (!TextUtils.isEmpty(c.getSname())) {
                    searchContent = c.getSname();
                }
                if (info != null && !TextUtils.isEmpty(info.searchKeys)) {
                    searchContent = info.searchKeys;
                }

                if (targetLat * targetLng != 0) {
                    // 后台分店已经自己设置了位置，仅求距离
                    LatLng llSelf = new LatLng(myLat, myLng);
                    LatLng llTarget = new LatLng(targetLat, targetLng);

                    float dis = AMapUtils.calculateLineDistance(llSelf, llTarget);
                    try {
                        int distance = (int) dis;
                        if (distance > 1000) {
                            float fd = distance / 1000f;
                            tDistance.setText(String.format("%.1f", fd) + "km");
                        } else {
                            tDistance.setText(distance + "m");
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                } else {
                    AMapWebApiManager.i().around(this, myLng, myLat, searchContent, new SubscriberAdapter<MapPOI>() {
                        @Override
                        public void onNext(MapPOI o) {
                            super.onNext(o);
                            Utils.logd("AMapWebApiManager around onNext");
                            if (TextUtils.equals("1", o.status) && o.pois != null && o.pois.size() > 0) {
                                MapPOI.POI poi = o.pois.get(0);

                                if (!TextUtils.isEmpty(poi.address) ||
                                        (poi.tel instanceof String && !TextUtils.isEmpty((String) poi.tel))) {
                                    lLineLocation.setVisibility((info != null && !TextUtils.isEmpty(info.officialWebsite)) ? View.VISIBLE : View.GONE);
                                    lLocation.setVisibility(View.VISIBLE);
                                    if (lOfficialWebSite.getVisibility() == View.GONE) {
                                        lSpacingLocation.setVisibility(View.VISIBLE);
                                    }
                                }
//                                else {
//                                    lLineLocation.setVisibility(View.GONE);
//                                    lLocation.setVisibility(View.GONE);
//                                }

                                if (!TextUtils.isEmpty(poi.address) && TextUtils.isEmpty(info.storeAdd)) {
                                    tAddress.setText(poi.address);
                                    lAddress.setVisibility(View.VISIBLE);
                                    try {
                                        int distance = Integer.parseInt(poi.distance);
                                        if (distance > 1000) {
                                            float fd = distance / 1000f;
                                            tDistance.setText(String.format("%.1f", fd) + "km");
                                        } else {
                                            tDistance.setText(distance + "m");
                                        }
                                    } catch (Exception e) {
                                        e.printStackTrace();
                                    }
                                }

                                if (poi.tel instanceof String && !TextUtils.isEmpty((String) poi.tel) && TextUtils.isEmpty(info.storePhone)) {
                                    try {
                                        tAddressTel.setText(((String) poi.tel).split(";")[0]);
                                        Utils.logd("AMapWebApiManager around tAddressTel.text =" + tAddressTel.getText().toString());
                                        lLineAddressTel.setVisibility(View.VISIBLE);
                                        lAddressTel.setVisibility(View.VISIBLE);
                                    } catch (Exception e) {
                                        e.printStackTrace();
                                    }
                                }
//                                else {
//                                    lLineAddressTel.setVisibility(View.GONE);
//                                    lAddressTel.setVisibility(View.GONE);
//                                }

                                if (!TextUtils.isEmpty(poi.location)) {
                                    try {
                                        targetLng = Double.parseDouble(poi.location.split(",")[0]);
                                        targetLat = Double.parseDouble(poi.location.split(",")[1]);
                                        targetCardName = c.getBusinessName();
                                        if (!TextUtils.isEmpty(c.getSname())) {
                                            targetCardName = c.getSname();
                                        }
                                        targetAddress = poi.address;
                                    } catch (Exception e) {
                                        e.printStackTrace();
                                    }
                                }
                            }
                        }
                    }.errorToast(false));
                }
            } else {
                locationResult = "location failure\n" +
                        "error code:" + loc.getErrorCode() + "\n" +
                        "error info:" + loc.getErrorInfo() + "\n" +
                        "error desc:" + loc.getLocationDetail();

                if (loc.getErrorCode() == 12) {
                    boolean isRemindDetailLocation = Utils.spReadBoolean("remind_detail_location", true);
                    if (isRemindDetailLocation) {
                        new AlertDialog.Builder(this).setTitle("提示").setMessage("缺少定位权限，无法为您获取附近该品牌商家门店信息")
                                .setNegativeButton("不再提醒", new DialogInterface.OnClickListener() {
                                    @Override
                                    public void onClick(DialogInterface dialog, int which) {
                                        Utils.spWrite("remind_detail_location", false);
                                        dialog.dismiss();
                                    }
                                })
                                .setPositiveButton("知道了", new DialogInterface.OnClickListener() {
                                    @Override
                                    public void onClick(DialogInterface dialog, int which) {
                                        dialog.dismiss();
                                    }
                                }).create().show();
                    }
                }
            }
        } else {
            locationResult = "location result is null";
        }
        Utils.logd("locationResult:%s", locationResult);
    }


    private void requestObtainCardShareUrl(final SHARE_MEDIA platform) {
        ApiManager.i().obtainCardShareUrl(this, App.i().getCurrUser().getUuid(), c.getMCardId(), new SubscriberAdapter<RespWrapper<CardShareInfo>>() {
            @Override
            public void onNext(RespWrapper<CardShareInfo> o) {
                super.onNext(o);
                if (o.code == C.http.RESULT_CODE_SUCCESS) {
                    String mName = "我";
                    if (App.i().getCurrUser() != null && !TextUtils.isEmpty(App.i().getCurrUser().getUserName())) {
                        mName = App.i().getCurrUser().getUserName();
                    }
                    String mCardName = isCustomMode ? c.getAnotherBusiness() : c.getBusinessName();
                    String mCardGrade = "会员卡";
                    if (!TextUtils.isEmpty(c.getGradeName()) && !TextUtils.equals("普通卡", c.getGradeName())) {
                        mCardGrade = c.getGradeName();
                    }
                    String mTitle = String.format("%s分享的%s%s", mName, mCardName, mCardGrade);
                    UMImage image = new UMImage(CardDetailActivity.this, isCustomMode ? c.getBuPic() : c.getMCardIcon());
                    new ShareAction(CardDetailActivity.this).setPlatform(platform)
                            .withText("不准外传！\n ▍▎▏▏▎▏▏▎▍")
                            .withTitle(mTitle)
                            .withTargetUrl(o.decode(CardShareInfo.class).shareMcardUrl)
                            .withMedia(image)
                            .setCallback(new UMShareListener() {
                                @Override
                                public void onResult(SHARE_MEDIA share_media) {
                                    Utils.onMobEvent(CardDetailActivity.this, "shareCardSucc", new String[]{"success"},
                                            new String[]{c.getBusinessId() + "_" + c.getMCardId()});
                                    Utils.showToast("分享成功");
                                }

                                @Override
                                public void onError(SHARE_MEDIA share_media, Throwable throwable) {
                                    Utils.onMobEvent(CardDetailActivity.this, "shareCardFail", new String[]{"fail"},
                                            new String[]{c.getBusinessId() + "_" + c.getMCardId()});
                                    Utils.showToast("分享失败");
                                }

                                @Override
                                public void onCancel(SHARE_MEDIA share_media) {
                                    Utils.onMobEvent(CardDetailActivity.this, "shareCardFail", new String[]{"fail"},
                                            new String[]{c.getBusinessId() + "_" + c.getMCardId()});
                                    Utils.showToast("分享取消");
                                }
                            }).share();
                }
            }
        }.showProgress(this));
    }

    @Override
    @OnClick({R.id.l_card_detail_item, R.id.l_address, R.id.i_code, R.id.l_address_tel, R.id.l_official_website, R.id.l_s, R.id.l_book, R.id.l_score})
    public void onClick(View v) {
        if (v == lRights) {
            if (info != null) {
                Utils.onMobEvent(this, "clickLinkOfDetail");
                Intent intent = new Intent(this, WebActivity.class);
                intent.putExtra("extra_url", info.rightUrl);
                startActivity(intent);
            }
        } else if (v == lCoupon) {
            if (info != null) {
                if (info.doCouponReceive == 0) {
                    Utils.onMobEvent(this, "clickLinkOfDetail");
                    Intent intent = new Intent(this, WebActivity.class);
                    intent.putExtra("extra_url", ServiceUrlProvider.obtainGoCouponReceiveUrl(c.getSid()));
                    startActivity(intent);
                } else {
                    Utils.onMobEvent(this, "clickLinkOfDetail");
                    Intent intent = new Intent(this, WebActivity.class);
                    intent.putExtra("extra_url", info.couponUrl);
                    startActivity(intent);
                }
            }
        } else if (v == lPrimaryPromotion) {
            if (info != null) {
                Utils.onMobEvent(this, "clickLinkOfDetail");
                Intent intent = new Intent(this, WebActivity.class);
                intent.putExtra("extra_url", info.bannerUrl);
                startActivity(intent);
            }
        } else if (v == lOfficialWebSite) {
            if (info != null) {
                Utils.onMobEvent(this, "clickLinkOfDetail");
                Intent intent = new Intent(this, WebActivity.class);
                intent.putExtra("extra_url", info.officialWebsite);
                startActivity(intent);
            }
        } else if (v == lCardDetailItem) {
            Utils.onMobEvent(this, "clickCardOfDetail");

            Utils.onMobEvent(this, "clickQRCodeOfDetail");
            Intent intent = new Intent(this, CardCodeActivity.class);
            intent.putExtra("extra_card", c);
            v.getContext().startActivity(intent);
        } else if (v == lAddress) {
            if (!TextUtils.isEmpty(tAddress.getText())) {
                if (myLat != 0 && myLng != 0 && targetLat != 0 && targetLng != 0) {
                    Utils.onMobEvent(this, "clickAddressOfDetail");
                    Intent intent = new Intent(this, AMapActivity.class);
                    intent.putExtra("extra_my_lat", myLat);
                    intent.putExtra("extra_my_lng", myLng);
                    intent.putExtra("extra_target_lat", targetLat);
                    intent.putExtra("extra_target_lng", targetLng);
                    intent.putExtra("extra_target_title", targetCardName);
                    intent.putExtra("extra_target_address", targetAddress);
                    intent.putExtra("extra_title", "门店信息");
                    startActivity(intent);
                }
            }
        } else if (v == iCode) {
            Utils.onMobEvent(this, "clickQRCodeOfDetail");
            Intent intent = new Intent(this, CardCodeActivity.class);
            intent.putExtra("extra_card", c);
            v.getContext().startActivity(intent);
        } else if (v == lAddressTel) {
            if (!TextUtils.isEmpty(tAddressTel.getText())) {
                Utils.onMobEvent(this, "clickPhoneOfDetail");
                Intent intent = new Intent(Intent.ACTION_DIAL, Uri.parse("tel:" + tAddressTel.getText().toString()));
                intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                startActivity(intent);
            }
        } else if (v == lS) {
            if (c != null) {
                Intent intent = new Intent(this, CardFDActivity.class);
                intent.putExtra("extra_card", c);
                startActivity(intent);
            }
        } else if (v == lBook) {
            // 通兑卡(消费卡)的预约跳转url链接 ， 显示预约item
            if (Card.STATUS_XIAOFEI.equals(c.getIsMyCard()) && info.doConsumerOrder == 0) {
                Intent intent = new Intent(this, WebActivity.class);
                intent.putExtra("extra_url", ServiceUrlProvider.obtainConsumerOrderUrl(c.getMCardId()));
                startActivity(intent);
            }
            // 然后 canOrderNum字段是分店卡(有sid的卡)的专属字段，判断值不为零表示该分店可以预约
            else if (c.getSid() != null && info.canOrderNum > 0) {
                Intent intent = new Intent(this, CardFDBookActivity.class);
                intent.putExtra("extra_card", c);
                startActivity(intent);
            }
        } else if (v == lScore) {
            // 给分店打分
            if (c != null) {
                Intent intent = new Intent(this, WebActivity.class);
                intent.putExtra("extra_url", ServiceUrlProvider.obtainGoScoreUrl(c.getSid()));
                startActivity(intent);
            }
        }
    }

    private void showSheetDialog() {
        if (dlgSheet == null) {
            SheetDialog.Builder builder = new SheetDialog.Builder(this);
            // 是收藏卡
            if (TextUtils.equals(c.getIsMyCard(), Card.STATUS_FAVORITE_CARD)) {
                builder.addMenu("放弃收藏", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                        Utils.onMobEvent(CardDetailActivity.this, "clickGiveupCollectionMenuOfCardDetails");
                        requestCancelStarCard();
                    }
                });
            }
            // 是最普通的卡
            else if (TextUtils.equals(c.getIsMyCard(), Card.STATUS_MY_CARD) && c.getSid() == null) {
                builder.addMenu("编辑", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                        Utils.onMobEvent(CardDetailActivity.this, "clickEditMenuOfCardDetails");
                        Intent intent = new Intent(CardDetailActivity.this, CardInfoEditActivity.class);
                        intent.putExtra("extra_card", App.i().getGson().toJson(c));
                        startActivity(intent);
                    }
                });
            }
            // 其它的 分店卡或者通兑卡
            else {
                builder.addMenu("删除会员卡", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                        requestDeleteCard();
                    }
                });
            }

            builder.addMenu("分享给好友", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    dialog.dismiss();

                    // 先提示 免责声明
                    new com.taokatao.cardmee.common.widget.AlertDialog.Builder(CardDetailActivity.this)
                            .setMessage("请谨慎分享会员卡，以免造成损失，是否继续分享？")
                            .setTitle("提示")
                            .setPositiveButton("继续", new DialogInterface.OnClickListener() {
                                @Override
                                public void onClick(DialogInterface dialog, int which) {
                                    dialog.dismiss();

                                    Utils.onMobEvent(CardDetailActivity.this, "clickShareMenuOfCardDetails", new String[]{"click"},
                                            new String[]{c.getBusinessId() + "_" + c.getMCardId()});
                                    new ShareDialog.Builder(CardDetailActivity.this)
                                            .setCallback(new ShareDialog.OnShareClickListener() {
                                                @Override
                                                public void onPlatformClick(Dialog dialog, SHARE_MEDIA platform) {
                                                    requestObtainCardShareUrl(platform);
                                                    dialog.dismiss();
                                                }
                                            }).create().show();
                                }
                            })
                            .setNegativeButton("取消", new DialogInterface.OnClickListener() {
                                @Override
                                public void onClick(DialogInterface dialog, int which) {
                                    dialog.dismiss();
                                }
                            }).create().show();

                }
            });

            dlgSheet = builder.create();
        }
        dlgSheet.show();
    }

    private void requestCancelStarCard() {
        if (App.i().getCurrUser() != null) {
            ApiManager.i().cancelStarCard(this, App.i().getCurrUser().getUuid(), c.getMCardId(), new SubscriberAdapter<RespWrapper<RespInfo>>() {
                @Override
                public void onNext(RespWrapper<RespInfo> o) {
                    super.onNext(o);
                    if (o.code == C.http.RESULT_CODE_SUCCESS) {
                        Utils.postMainThreadBusEvent(BusEvent.CARD_DELETE, c);
                        finish();
                    }
                }
            }.showProgress(this));
        }
    }

    private void requestObtainCardDetail() {
        if (App.i().getCurrUser() != null) {
            ApiManager.i().obtainCardDetail(this, App.i().getCurrUser().getUuid(), c.getMCardId(), c.getBusinessId(), c.getSid(),
                    c.getIsMyCard(), new SubscriberAdapter<RespWrapper<CardDetailInfo>>() {
                        @Override
                        public void onNext(RespWrapper<CardDetailInfo> o) {
                            super.onNext(o);
                            Utils.logd("obtainCardDetail#onNext in activity");
                            if (o.code == C.http.RESULT_CODE_SUCCESS) {
                                info = o.decode(CardDetailInfo.class);
                                if (!TextUtils.isEmpty(o.message)) {
                                    info.searchKeys = o.message;
                                }
                                resetDetailInfo();
                            }
                        }
                    }.errorToast(false));
        }
    }

    /**
     * 根据http请求得到卡片详细信息(CardDetailInfo info) 来填充显示界面
     */
    private void resetDetailInfo() {
        if (info == null) return;

        // app自测数据
//        info.rightTitle = "权益";
//        info.rightUrl = "www.baidu.com";
//        info.couponName = "优惠券";
//        info.couponDec = "95折";
//        info.hMemberTitleList = new ArrayList<>();
//        CardDetailInfo.Tag ttt = new CardDetailInfo.Tag();
//        ttt.titleName = "dakdas";
//        info.hMemberTitleList.add(ttt);
//        info.hMemberBannerSubsetList = new ArrayList<>();
//        CardDetailInfo.Promotion p1 = new CardDetailInfo.Promotion();
//        p1.bannerName = "子活动1号";
//        p1.bannerUrl = "www.sina.com";
//        CardDetailInfo.Promotion p2 = new CardDetailInfo.Promotion();
//        p2.bannerName = "收集五福分2亿大奖";
//        info.hMemberBannerSubsetList.add(p1);
//        info.hMemberBannerSubsetList.add(p2);
//        info.cardBannerList = new ArrayList<>();
//        CardDetailInfo.Banner bbb1 = new CardDetailInfo.Banner();
//        bbb1.bannerName = "通用banner";
//        CardDetailInfo.Banner bbb2 = new CardDetailInfo.Banner();
//        bbb2.bannerName = "第二个通用banner";
//        bbb2.bannerDec = "描述";
//        bbb2.bannerUrl = "www.qq.com";
//        info.cardBannerList.add(bbb1);
//        info.cardBannerList.add(bbb2);boo
//        info.latItude = "31.177983";
//        info.longItude = "121.423656";
//        info.storePhone = "18888881234";
//        CardDetailInfo.CourseOrdered ordered1 = new CardDetailInfo.CourseOrdered();
//        ordered1.courseName = "天天向上";
//        ordered1.teacherName = "汪涵";
//        ordered1.classTime = 20170208220000l;
//        CardDetailInfo.CourseOrdered ordered2 = new CardDetailInfo.CourseOrdered();
//        ordered2.courseName = "动物世界";
//        ordered2.teacherName = "abc";
//        ordered2.classTime = 20171115233000l;
//        info.courseOrderedList = new ArrayList<>();
//        info.courseOrderedList.add(ordered1);
//        info.courseOrderedList.add(ordered2);

        lSpacingLocation.setVisibility(View.GONE);
        if (TextUtils.isEmpty(info.officialWebsite)) {
            lOfficialWebSite.setVisibility(View.GONE);
        } else {
            lOfficialWebSite.setVisibility(View.VISIBLE);
        }

        // 有自己的设置过的经纬度(分店)
        if (!TextUtils.isEmpty(info.storeAdd) ||
                !TextUtils.isEmpty(info.storePhone)) {
            lLineLocation.setVisibility((info != null && !TextUtils.isEmpty(info.officialWebsite)) ? View.VISIBLE : View.GONE);
            lLocation.setVisibility(View.VISIBLE);
            if (lOfficialWebSite.getVisibility() == View.GONE) {
                lSpacingLocation.setVisibility(View.VISIBLE);
            }
        } else {
            lLineLocation.setVisibility(View.GONE);
            lLocation.setVisibility(View.GONE);
        }

        if (!TextUtils.isEmpty(info.storeAdd)) {
            tAddress.setText(info.storeAdd);
            lAddress.setVisibility(View.VISIBLE);
        }

        if (!TextUtils.isEmpty(info.storePhone)) {
            try {
                tAddressTel.setText(info.storePhone);
                lLineAddressTel.setVisibility(View.VISIBLE);
                lAddressTel.setVisibility(View.VISIBLE);
            } catch (Exception e) {
                e.printStackTrace();
            }
        } else {
            lLineAddressTel.setVisibility(View.GONE);
            lAddressTel.setVisibility(View.GONE);
        }

        if (!TextUtils.isEmpty(info.latItude) && !TextUtils.isEmpty(info.longItude)) {
            try {
                targetLng = Double.parseDouble(info.longItude);
                targetLat = Double.parseDouble(info.latItude);
                targetCardName = c.getBusinessName();
                if (!TextUtils.isEmpty(c.getSname())) {
                    targetCardName = c.getSname();
                }
                targetAddress = info.storeAdd;
            } catch (Exception e) {
                e.printStackTrace();
            }
        }


        if (!isCustomMode && !hasStartLocation) {
            // 定位走一发，然后通过高德Api根据关键字搜索店信息(不准)

            hasStartLocation = true;

            if (!AndPermission.hasPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION)) {
                AndPermission.with(this)
                        .requestCode(CODE_FOR_LOCATION_PERMISSION)
                        .permission(Manifest.permission.ACCESS_COARSE_LOCATION)
                        .send();
            } else {
                locationClient.startLocation();
            }
        }

        if (info.productAllNum != null) {
            lS.setVisibility(View.VISIBLE);

            String value;
            if (info.balance <= 0) {
                value = "0.00";
            } else if (info.balance % 1 == 0) {
                value = String.valueOf((int) info.balance);
            } else {
                value = String.valueOf(info.balance);
            }
            tBalance.setText(value);

            tProductCount.setText(String.valueOf(info.productAllNum));
            tIntegral.setText(String.valueOf(info.integral));
        } else {
            lS.setVisibility(View.GONE);
        }

        // 通兑卡(消费卡)的预约跳转url链接 ， 显示预约item
        if (Card.STATUS_XIAOFEI.equals(c.getIsMyCard()) && info.doConsumerOrder == 0) {
            lBook.setVisibility(View.VISIBLE);
        }
        // 然后 canOrderNum字段是分店卡(有sid的卡)的专属字段，判断值不为零表示该分店可以预约
        else if (c.getSid() != null && info.canOrderNum > 0) {
            // 分店预约
            lBook.setVisibility(View.VISIBLE);
            lSubCourses.removeAllViewsInLayout();
            if (info.courseOrderedList != null) {
                for (int i = 0; i < info.courseOrderedList.size(); i++) {
                    CardDetailInfo.CourseOrdered courseOrdered = info.courseOrderedList.get(i);
                    if (courseOrdered != null && !TextUtils.isEmpty(courseOrdered.getDescString())) {

                        if (i < info.courseOrderedList.size()) {
                            LayoutInflater.from(this).inflate(R.layout.layout_septal_line, lSubCourses);
                        }
                        CardDetailCourseLayout lSubCourse = new CardDetailCourseLayout(this);
                        lSubCourse.setData(courseOrdered, info.doOrderDetail == 0);
                        lSubCourses.addView(lSubCourse);
                    }
                }
            }
        } else {
            lBook.setVisibility(View.GONE);
        }

        if (TextUtils.isEmpty(info.rightTitle) ||
                (TextUtils.isEmpty(info.rightDec) && TextUtils.isEmpty(info.rightUrl) && (info.hMemberTitleList == null || info.hMemberTitleList.size() < 1))) {
            lRights.setVisibility(View.GONE);
        } else {
            lRights.setVisibility(View.VISIBLE);
            tRightsTitle.setText(info.rightTitle);
            tRightsDesc.setText(info.rightDec);
            tRightsTags.setText("");
            if (info.hMemberTitleList != null) {
                for (CardDetailInfo.Tag tag : info.hMemberTitleList) {
                    if (tag != null && !TextUtils.isEmpty(tag.titleName)) {
                        SpannableString tagSpan = new SpannableString(tag.titleName);
                        tagSpan.setSpan(new BackgroundColorSpan(0xFFFE356D), 0, tag.titleName.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
                        tRightsTags.append(tagSpan);
                        tRightsTags.append(" ");
                    }
                }
            }
            if (TextUtils.isEmpty(info.rightUrl)) {
                iRightUrl.setVisibility(View.GONE);
                lRights.setOnClickListener(null);
            } else {
                iRightUrl.setVisibility(View.VISIBLE);
                lRights.setOnClickListener(this);
            }
        }

        // 分店优惠券
        if (c.getSid() != null && info.doCouponReceive == 0) {
            lCoupon.setVisibility(View.VISIBLE);
            tCouponTitle.setText("领取优惠券");
            tCouponDesc.setText("");
            iCouponUrl.setVisibility(View.VISIBLE);
            lCoupon.setOnClickListener(this);
        } else if (!TextUtils.isEmpty(info.couponName) && (!TextUtils.isEmpty(info.couponDec) || !TextUtils.isEmpty(info.couponUrl))) {
            // 普通卡的优惠券，或者说其它卡的通用优惠券 通过couponName 判断
            lCoupon.setVisibility(View.VISIBLE);
            tCouponTitle.setText(info.couponName);
            tCouponDesc.setText(info.couponDec);
            if (TextUtils.isEmpty(info.couponUrl)) {
                iCouponUrl.setVisibility(View.GONE);
                lCoupon.setOnClickListener(null);
            } else {
                iCouponUrl.setVisibility(View.VISIBLE);
                lCoupon.setOnClickListener(this);
            }

        } else {
            lCoupon.setVisibility(View.GONE);
        }

        // 给分店打分
        if (c.getSid() != null && info.doScore == 0) {
            lScore.setVisibility(View.VISIBLE);
        } else {
            lScore.setVisibility(View.GONE);
        }

        if (TextUtils.isEmpty(info.bannerName)) {
            lPromotion.setVisibility(View.GONE);
        } else {
            lPromotion.setVisibility(View.VISIBLE);
            tPromotionTitle.setText(info.bannerName);
            tPromotionDesc.setText(info.bannerDec);
            if (TextUtils.isEmpty(info.bannerUrl)) {
                iPromotionUrl.setVisibility(View.GONE);
                lPrimaryPromotion.setOnClickListener(null);
            } else {
                iPromotionUrl.setVisibility(View.VISIBLE);
                lPrimaryPromotion.setOnClickListener(this);
            }

            // 是否有图片类型的广告
            boolean hasCoverItem = false;
            lAds.removeAllViews();
            if (info.adList != null) {
                for (int i = 0; i < info.adList.size(); i++) {
                    CardDetailInfo.AD ad = info.adList.get(i);
                    if (ad != null && !TextUtils.isEmpty(ad.adCover)) {
                        CardDetailADLayout1 lAdImage = new CardDetailADLayout1(this);
                        lAdImage.setData(ad);
                        lAds.addView(lAdImage);
                        hasCoverItem = true;
                    } else {
                        if (i < info.adList.size()) {
                            LayoutInflater.from(this).inflate(R.layout.layout_septal_line, lAds);
                        }
                        CardDetailADLayout2 lAdText = new CardDetailADLayout2(this);
                        lAdText.setData(ad);
                        lAds.addView(lAdText);
                    }
                }
            }

            // 是否有子活动
            boolean hasSubPromotions = false;
            lSubPromotions.removeAllViewsInLayout();
            if (info.hMemberBannerSubsetList != null) {
                for (int i = 0; i < info.hMemberBannerSubsetList.size(); i++) {
                    CardDetailInfo.Promotion promotion = info.hMemberBannerSubsetList.get(i);
                    if (promotion != null && !TextUtils.isEmpty(promotion.bannerName)) {
                        hasSubPromotions = true;
                        if (i < info.hMemberBannerSubsetList.size()) {
                            if (!hasCoverItem || i > 0) {
                                LayoutInflater.from(this).inflate(R.layout.layout_septal_line, lSubPromotions);
                            }
                        }
                        CardDetailSubPromotionLayout lSubPromotion = new CardDetailSubPromotionLayout(this);
                        lSubPromotion.setData(promotion);
                        lSubPromotions.addView(lSubPromotion);
                    }
                }
            }

            lBanner.removeAllViewsInLayout();
            if (info.cardBannerList != null) {
                for (int i = 0; i < info.cardBannerList.size(); i++) {
                    CardDetailInfo.Banner banner = info.cardBannerList.get(i);
                    if (banner != null) {
                        if (i < info.cardBannerList.size()) {
                            if (!hasCoverItem || hasSubPromotions || i > 0) {
                                LayoutInflater.from(this).inflate(R.layout.layout_septal_line, lBanner);
                            }
                        }
                        CardDetailBannerLayout lBannerItem = new CardDetailBannerLayout(this);
                        lBannerItem.setData(banner);
                        lBanner.addView(lBannerItem);
                    }
                }
            }
        }

    }

    @Override
    protected void onLocationPermissionAllowed() {
        if (!locationClient.isStarted()) {
            locationClient.startLocation();
        }
    }

    // 初始设置所有卡的相同公有模块的值和对应的UI
    private void resetBasicInfo() {
        if (isCustomMode) {
            styleColor = 0xFF4C4C4C;
            tCardName.setText(c.getAnotherBusiness());
            if (!TextUtils.isEmpty(c.getBuPic())) {
                iLogo.setVisibility(View.VISIBLE);
                Glide.with(iLogo.getContext()).load(c.getBuPic()).into(iLogo);
            }
        } else {
            if (!TextUtils.isEmpty(c.getBackColor()) && c.getBackColor().length() == 7 && c.getBackColor().startsWith("#")) {
                styleColor = Color.parseColor(c.getBackColor());
            } else {
                styleColor = 0xFF4C4C4C;
            }
            tCardName.setText(c.getBusinessName());
            // 分店名称
            if (!TextUtils.isEmpty(c.getSname())) {
                tCardName.setText(c.getSname());
            }

            iLogo.setVisibility(View.VISIBLE);
            Glide.with(iLogo.getContext()).load(c.getMCardIcon()).bitmapTransform(App.i().getCropCircleTransformation()).into(iLogo);

        }
        boolean blackColorStyle = Utils.isDarkColorTheme(styleColor);
        if (!blackColorStyle) {
            styleColor = 0xFF242424;
        }
        iBackground.setImageDrawable(new ColorDrawable(styleColor));
        iCode.setImageResource(blackColorStyle ? R.mipmap.card_code_white : R.mipmap.card_code_black);
        String cardNumber = TextUtils.isEmpty(c.getMCardNo()) ? "" : c.getMCardNo();
        tNumber.setText("NO." + Utils.formatCardCode(cardNumber));

        if (!TextUtils.isEmpty(c.getGradeName()) && !TextUtils.equals("普通卡", c.getGradeName())) {
            tGrade.setVisibility(View.VISIBLE);
            tGrade.setText(c.getGradeName());
        } else {
            tGrade.setVisibility(View.GONE);
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        locationClient.unRegisterLocationListener(this);
    }

    private void requestDeleteCard() {
        ApiManager.i().deleteCard(this, App.i().getCurrUser().getUuid(), c.getMCardId(),c.getIsMyCard(), new SubscriberAdapter<RespWrapper<RespInfo>>() {
            @Override
            public void onNext(RespWrapper<RespInfo> o) {
                super.onNext(o);
                if (o.code == C.http.RESULT_CODE_SUCCESS) {
                    Utils.postMainThreadBusEvent(BusEvent.CARD_DELETE, c);
                    ActivityCollector.finishAllExcept(MainActivity.class);
                }
            }
        }.showProgress(this));
    }
}
